<?php
/**
 * 栏目操作
 * @author M2
 * @version 1.0
 * create Date 2013-07-22
 */
class CateAction extends PublicAction {
	
	/**
	 * 站点栏目列表
	 */
	public function sitecatelist(){
		$sid = M('cms_site')->getField("siteid");
		$this->assign("sid",$sid);
		$this->display();
	}
    /**
     * 栏目列表
     * M2
     */
    public function catelist() {
        $siteList = D('Site')->getSiteListArr('sitetemplatelist');
        $sid = intval($_GET['sid']);
        if ($sid && $sid > 0) {
        	$sited = M('cms_site')->where('siteid=' . $sid)->find();
            $db = M('cms_category');
            if(!empty($_GET['id'])) {
                $id = $db->where('siteid='.$sid.' and id='.intval($_GET['id']))->getField('pid');
            } else {
                $id = $db->where('siteid='.$sid.' and pid=0')->getField('id');
            }
            $pid = isset($_GET['pid']) && !empty($_GET['pid']) ? intval($_GET['pid']) : $id;
            if($pid!=$db->where('siteid='.$sid.' and pid=0')->getField('id')) {
                $this->assign('blo',true);
            }
            $map['pid'] = $pid;
            $map['siteid'] = $sid;
            $list = $db ->field('(case when url <> "" then url when createurl <> "" then createurl
                    else (concat("' . $sited['domain'] . '","/",replace(catenaming,"{cateid}",id))) end) as cateurl,
                    replace(imageurl,"@","' . $sited['domain'] . '") as imageurl,catenaming,id,cname,content,keywords,siteid,
                    description,catetemplate,arttemplate,createurl,catenaming,artnaming,pagetitle,pagedescription,
            		inputtime,updatetime,content_num,pid')->where($map)->order('display_order')->select();
            //得到全局配置
            $changeStyle = model('Data')->get('cmsconfig:site-' . $sid);
            foreach ($list as $k=>$v){
            	if(empty($v['catenaming'])){
                     $catenaming  = common('Array')->getParseTemplate($v, $changeStyle['catenaming'], 'cateid');
                     $create_name = str_replace('{@ChannelID}', $v['id'], $catenaming);
                     $create_name = str_replace('{@Year}', date("Y"), $create_name);
                     $list[$k]['cateurl'] =$sited['domain'].'/'.$create_name;
                    }
                    $list[$k]['cateurl'] =str_replace('{@ChannelID}', $v['id'],   $list[$k]['cateurl']);
            } 
            unset($map);
            $map['id'] = $pid;
            $location = $this->getLocation($pid,$sid);
            $this->assign('location',$location);
            $cid = $list[0]['pid'];
            $this->assign('cid',$pid);
            
            $curdomain = M('cms_site') ->where("siteid = ".$sid) -> getField("domain");
            $domain = M('cms_site') ->where("siteid = 1") -> getField("domain");
            foreach ($list as $k => $v){
                if(strpos($v['imageurl'],"@") ===0){
                    $list[$k]['imageurl'] = $curdomain.substr($list[$k]['imageurl'],1);
                }elseif (strpos($v['imageurl'],"/") ===0){
                    if(strpos($v['imageurl'],__ROOT__."/") ===0)
                        continue;
                    $list[$k]['imageurl'] = $curdomain.$list[$k]['imageurl'];
                }elseif (strpos($v['imageurl'],"~") ===0){
                    $list[$k]['imageurl'] = $domain.$list[$k]['imageurl'];
                }
            }
            
            $this->assign('list',$list);
            $this->assign('ssid',$sid);
        }
        $this->assign('sitelist', $siteList);
        $this->display();
    }
    public function getLocation($id,$sid) {
        $cid = M('cms_category')->where('siteid='.$sid.' and pid=0')->getField('id');
        $sitename = M('cms_site')->where('siteid='.$sid)->getField('name');
        $parseStr = $sitename;
        if($id == $cid) return $parseStr;
        $list = M('cms_category')->field("concat(plistid,'-',id) as bpath")->where(array('id'=>$id))->find();
        $str = strtr(ltrim($list['bpath'],'0-'),array('-'=>','));
        $str = str_replace($cid.',','',$str);
        $map['id'] = array('in',$str);
        $list = M('cms_category')->field("concat(plistid,'-',id) as bpath,cname,id,pid,createurl,catenaming,artnaming")->where($map)->order('bpath')->select();
        $list = array_reverse($list);
        foreach($list as $k=>$v) {
            $parseStr.= " >> <a href='".URL('cms/Cate/catelist',array('pid'=>$v['pid'],'sid'=>$sid))."'>{$v['cname']}</a>";
        }
        return $parseStr;
    }
    /**
     * 添加栏目页
     * M2
     */
    public function addcate() {
        $sid = intval($_GET['sid']);
        $data['siteid'] = $sid;
        $this->getTemplateFileName($data,intval($_GET['pid']),$sid);
        $config = model('Data')->get('cmsconfig:site-'.$sid);
        $this->assign('pid',intval($_GET['pid']));
        $this->assign('sid',intval($_GET['sid']));
        $this->assign($config);
        $this->display();
    }
    /**
     * 添加栏目操作页
     * M2
     */
    public function doaddcate() {
        if($_POST) {
            $sid = intval($_POST['sid']);
            $data['siteid'] = $sid;
            $pid = intval($_POST['pid']) == 0?0:intval($_POST['pid']);
            $data['pid'] = $pid;
            if(intval($_POST['pid']) == 0) {
                $data['plistid'] = '0';
            } else {
                $list = M('cms_category')->where("id=$pid")->find();
                $data['plistid'] = empty($list['plistid']) ? $list['id'] : $list['plistid'].','.$list['id'];
            }
            $cname = common('Html')->text($_POST['cname']);
            if(!empty($_POST['id'])) {
                $id = intval($_POST['id']);
                $map['id'] = array('neq',$id);
                $map['cname'] = $cname;
                $findcname = M('cms_category')->where($map)->find();
            } else {
                $findcname = M('cms_category')->where("cname=".$cname." and siteid=".$sid)->find();
            }
            if($findcname)
                $this->error('栏目名称已存在');
            $cmsconfig = model('Data')->get('cmsconfig:site-'.$sid);
            $data['cname'] = common('Html')->text($_POST['cname']);
            $data['pagedescription'] = common('Html')->text($_POST['pagedescription']);
            $data['keywords'] = common('Html')->text($_POST['keywords']);
            $data['pagetitle'] = common('Html')->text($_POST['pagetitle']);
            $data['description'] = common('Html')->text($_POST['description']);
            $data['url'] = empty($_POST['url'])?'':$_POST['url'];
            $data['catetemplate'] = empty($_POST['channels'])?$cmsconfig['channelTemplate']:common('Html')->text($_POST['channels']);
            $data['arttemplate'] = empty($_POST['contents'])?$cmsconfig['contentTemplate']:common('Html')->text($_POST['contents']);
            $data['createurl'] = common('Html')->text($_POST['createurl']);
            $data['catenaming'] = empty($_POST['catenaming'])?$cmsconfig['catenaming']:common('Html')->text($_POST['catenaming']);
            $data['artnaming'] = empty($_POST['artnaming'])?$cmsconfig['artnaming']:common('Html')->text($_POST['artnaming']);
            $data['content'] = htmlspecialchars_decode($_POST['content']);
            $data['group_name_collection'] = empty($_POST['group_name_collection'])?"":implode(",",$_POST['group_name_collection']);
            if(!empty($_POST['id'])) {
                $data['update_uid'] = $this->mid;
                $data['update_uname'] = common('String')->getUserName($this->mid);
                $data['updatetime'] = time();
            } else {
                $data['create_uid'] = $this->mid;
                $data['create_uname'] = common('String')->getUserName($this->mid);
                $data['update_uid'] = $this->mid;
                $data['update_uname'] = common('String')->getUserName($this->mid);
                $data['inputtime'] = time();
                $data['updatetime'] = time();
            }
            $data['imageurl'] = $_POST['imageurl'];
            if(!empty($_POST['id'])) {
                $id = intval($_POST['id']);
                $saveCate = M('cms_category')->where('id='.$id)->save($data);
                if(false !== $saveCate) {
                    S('catelist'.$sid,NULL);
                    S('cache_channel_'.$id, null);
                    S('cache_channelname_'.$sid.'_'.$data['cname'], null);
                    if($cmsconfig['createchannel'] == '1' && $data['url'] =='') {
                        $this->createChannelsPage($id,$sid);
                    }
                    $this->assign('jumpUrl',URL('cms/Cate/catelist',array('pid'=>$pid,'sid'=>$sid)));
                    $this->success('操作成功');
                } else {
                    $this->error('操作失败');
                }
            } else {
                if($id=M('cms_category')->add($data)) {
                    M('cms_category')->where('id='.$id)->setField('display_order',$id);
                    S('catelist'.$sid,NULL);
                    if($cmsconfig['createchannel'] == '1' && $data['url'] =='') {
                        $this->createChannelsPage($id,$sid);
                    }
                    $this->assign('jumpUrl',URL('cms/Cate/catelist',array('pid'=>$pid,'sid'=>$sid)));
                    $this->success('操作成功');
                } else {
                    $this->error('操作失败');
                }
            }
        } else {
            $this->error('操作失败');
        }
    }
    /**
     * 修改栏目展示页
     * M2
     */
    public function updateCate() {
        if(empty($_GET['id']))
            $this->error('栏目不存在');
        $id = intval($_GET['id']);
        $findCate = M('cms_category')->where('id='.$id)->find();
        $data['siteid'] = intval($_GET['sid']);
        $this->getTemplateFileName($data,$findCate['pid'],intval($_GET['sid']));
        $this->assign('sid',intval($_GET['sid']));
        $this->assign('id',$id);
        $this->assign('pid',$findCate['pid']);
        $findCate['channelTemplate'] = $findCate['catetemplate'];
        $findCate['contentTemplate'] = $findCate['arttemplate'];
        $categroup = explode(",",$findCate['group_name_collection']);
        $this->assign("categroup",$categroup);
        $this->assign($findCate);
        $this->display('addcate');
    }
    /**
     * 删除栏目
     * M2
     */
    public function delCate() {
        if (empty ( $_POST ['ids'] )) {
            echo 0;
            exit ();
        }
        $data['id'] = array('in',$_POST['ids']);
        $list = M('cms_category')->where($data)->select();
        if(empty($list)) {
            echo 0;
            exit();
        }
        foreach ($list as $k => $v) {
            $filename = $v['imageurl'];
            if(file_exists($filename))
                unlink($filename);
        }
        S('catelist'.$_POST['sid'],NULL);
        
        echo M('cms_category')->where($data)->delete() ? '1' : '0';
    }
    /**
     * 上传图片、视频、swf
     * M2
     */
    public function uploadPic() {
        uploadPic('./data/cms/upload/','data/cms/upload/');
    }
    /**
     * 获取服务器端图片
     * M2
     */
    public function getServerPic() {
        getServerPic('./data/cms/upload/','data/cms/upload/');
    }
    
    /**
     * 将站点列表封装成tree
     * sun
     */
    public function catesList() {
        //得到内容列表的权限
        $rid = M('role_user') -> where("user_id =".$_SESSION['mid']) -> field("role_id") -> select();
        if($rid){
        	$ids = "";
        	foreach ($rid as $v){
        		$ids.= $v['role_id'].',';
        	}
        	$ids=substr($ids,0, strlen($ids)-1);
            $sids = M('access') ->join(" as a left join ".C ( 'DB_PREFIX' ) ."node as n on a.node_id = n.id")
            -> where(" a.role_id in (".$ids.") and a.level=3 and n.name='contentlist'") -> field("n.sid") -> select();
        }
        if(empty($sids)){
            $sitelist = M('cms_site')->order('siteid asc')->select();
        }else{
            foreach ($sids as $k => $v){
                $sids[$k] = $v['sid'];
            }
            $map['siteid'] = array('in',implode(",",$sids));
            $sitelist = M('cms_site')->where($map)->order('siteid asc')->select();
        }
        $arr = array();
        //得到站点列表
        foreach ($sitelist as $k => $v) {
            $arr['siteid'][] = $v['siteid'];
            $arr['name'][] = $v['name'];
        }
        $siteid = implode(',', $arr['siteid']);

        echo D('Category')->getCateTreeList($siteid,$arr['name']);
    	/*$sitelist = M('cms_site')->select();
        $slist = array();
        foreach ($sitelist as $key => $value) {
            $slist[$key]['id'] = $value['siteid'];
            $slist[$key]['text'] = $value['name'];
            $clist = M('cms_category')->where('siteid='.$value['siteid'])->field('id, cname, pid')->select();
            $slist[$key]['children'] = tree($clist, 0);
        }
        echo json_encode($slist);*/
    }
    
    /**
     * 将栏目列表封装成tree
     * M2
     */
    public function cateTreeList() {
        $sid = intval($_GET['sid']);
        echo D('Category')->getCateList($sid);
    }
    
    
    /**
     * 栏目列表排序
     * M2
     */
    public function display_order() {
        display_order('cms_category');
    }
    /**
     * 添加成功后生成栏目页
     * M2
     * @param $id
     */
    public function createChannelsPage($id,$sid) {
        if(empty($id))
            $this->error('请选择要生成的栏目');
        $data['siteid'] = $sid;
        $data['id'] = array('eq',$id);

        //得到全局配置
        $changeStyle = model('Data')->get('cmsconfig:site-'.$sid);
        
        //得到站点信息
        if (($sited = S('cache_siteid_'.$sid)) === false) {
        	$sited = M('cms_site')->where('siteid='.$sid)->find();
        	S('cache_siteid_'.$sid, $sited);
        }        
        
        //得到栏目资料
        $list = M('cms_category')
            ->field('(case when url <> "" then url when createurl <> "" then createurl
  else (concat("'.$sited['domain'].'","/",replace(replace((case when catenaming <> "" then catenaming else ("'.$changeStyle['catenaming'].'") end),"{@ChannelID}",id),"{cateid}",id))) end) as cateurl,
  replace(imageurl,"@","'.$sited['domain'].'") as imageurl,id,cname,content,keywords,
  description,catetemplate,arttemplate,createurl,catenaming,artnaming,
  inputtime,updatetime,content_num,pid')
            ->where($data)
            ->find();

        if(empty($list)) $this->error('栏目不存在');

        //缓存栏目信息
        S('cache_channel_'.$id, $list);
        
        //得到栏目所属模板
        if ($list['catetemplate']) {
        	$list['catetemplate'] = iconv("UTF-8","GB2312",$list['catetemplate']);
        } else {
        	$list['catetemplate'] = iconv("UTF-8","GB2312",$changeStyle['channelTemplate']);
        }
        
        //得到栏目生成路径
        if(!empty($list['createurl'])) {
        	$create_name = $list['createurl'];
        } else {
        	//栏目命名规则没有时，用全局配置
            if (!$list['catenaming']) {
                $list['catenaming'] = $changeStyle['catenaming'];
            }
            $create_name = str_replace('{@ChannelID}',$list['id'],$list['catenaming']);
            $create_name = str_replace('{cateid}', $list['id'], $create_name);
            $create_name = str_replace('{@Year}',date("Y"), $create_name);
        }
        
        //得到站点目录
        $createdir = empty($sited['dirname'])?'':$sited['dirname'].'/';
        $createdir = './'.$createdir;
        //得到站点模板目录
        $templatedir = $createdir.'templates/';
        
        //包含文件
        $content = taglib('YlInclude')->parse($templatedir.$list['catetemplate'],'',$templatedir);
        $content = taglib('YlInclude')->parse('',$content,$templatedir);
        $content = taglib('YlInclude')->parse('',$content,$templatedir);
        
        $content = taglib('YlSite')->parse($content,$sid);
        $content = taglib('YlSearchInput')->parse($content,$sid);
        
        $content = taglib('YlLocation')->parse($content,$sid,$list['id']);
        $content = taglib('YlNavigation')->parse($content,$sid,$list['id'], '', $sited['domain'], $changeStyle);
        $content = taglib('YlChannels')->parse($content,$sid,$list['id'],$changeStyle);
        if(strpos($content,'{') && strpos($content,'}')) {
            preg_match_all('/\{site.(.*?)\}/eis',$content,$out);
            for ($i=0; $i< count($out[1]); $i++) {
                $content = str_replace($out[0][$i],$sited[$out[1][$i]],$content);
            }
            preg_match_all('/\{Channel.(.*?)\}/eis',$content,$match);
            for ($i=0; $i< count($match[1]); $i++) {
                $content = str_replace($match[0][$i],$list[$match[1][$i]],$content);
            }
        }
        
        $content = taglib('YlAd')->parse($content, $sid);
        
        $content = taglib('YlContents')->parse($content,$sid,$list,$sited['domain'],$changeStyle);
        $content = taglib('YlSqlContents')->parse($content);
        
        $content = taglib('YlBlock')->parse($content,$sid,$sited['domain'],$changeStyle);
        
        $content = taglib('YlPageContents')->parse($content,$list['id'],$sid,$$list,$createdir,$sited['domain'],$changeStyle, $create_name);
        if(!empty($content)) {
            $content = taglib('YlPageSqlContents')->parse($content,$list['id'],$sid,$list,$createdir,$sited['domain'],$changeStyle, $create_name);
            if (!empty($content)) {
               $content = taglib('YlA')->parse($content,$sid,$list,'4',$sited['domain'],$changeStyle);
               $content = taglib('YlImage')->parse($content,$list, $sid);                                             
               $content = taglib('YlCount')->parse($content,$list);
               $content = taglib('YlIf')->parse($content, $list);                              
               $content = taglib('YlChannel')->parse($content,$list,$sid,$sited['domain'],$changeStyle);
                if(dirname($createdir.$create_name))
                    mk_dir(dirname($createdir.$create_name));
                file_put_contents($createdir.$create_name,$content);
            }
        }
    }
    private function getTemplateFileName($data,$pid=0,$sid) {
        $channelsTemplate = M('cms_templates')->where("siteid = ".$sid." and template_type='channels'")->select();
        $contentsTemplate = M('cms_templates')->where("siteid = ".$sid." and template_type='contents'")->select();
        $grouplist = model('Group') -> getGroupList($sid);
        $list = D('Category')->channelList($data);
        $string = "<select id='pid' name='pid' style='width: 200px;'>";
        $str = "<option value='\$id' \$selected>\$spacer \$cname</option>;";
        import('Tree');
        $tree = new Tree();
        $tree->init($list);
        $string .= $tree->get_tree_multi(0, $str,$pid);
        $string .= "</select>";
        $this->assign('alist',$string);
        $this->assign('channelsTemplate',$channelsTemplate);
        $this->assign('contentsTemplate',$contentsTemplate);
        $this->assign('grouplist',$grouplist);
    }
}
?>
